#!/usr/bin/env python
# --*-- encoding:utf-8 --*-- 

'''
Created on 2011-12-31
@author: fredzhu.com
'''

u'''
    程序基于https://webim.feixin.10086.cn/login.aspx发送消息.不记录密码
'''

from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from django.utils import simplejson as json
from django.conf import settings

from fetion.models import FetionStatus,SMSQueue,TaskCron
from fetion.models import FETION_STATUS_ENUM,TASK_ENUM
from fetion.webim import FetionWebIM
from fetion.mail import send_mail

import xmlrpclib
import logging,random
logger = logging.getLogger('fetion')

proxy = xmlrpclib.ServerProxy("http://localhost:%s/"%settings.RPC_PORT, allow_none=True)

#------------内部方法--------------
def auth(fn):
    def check(*args):
        request = args[0]
        phone = request.session.get('phone',None)
        #没登录
        if not phone:
            result = {"statusCode":301,"message":u"请先登录","navTabId":"","rel":"","callbackType":"","forwardUrl":""}
            return HttpResponse(json.dumps(result))
        return fn(*args)
    return check
#----------------------------------

FETION_URL = u"https://webim.feixin.10086.cn/WebIM/Login.aspx"

def index(request):
    return render_to_response('fetion/index.html',context_instance=RequestContext(request))

def logout(request):
    u'''退出
    '''
    request.session.clear()
    return HttpResponseRedirect('/')

def login(request):
    u'''登录系统
    '''
    if request.method == 'POST':
        result = {"navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}

        phone = request.POST.get('phone')
        security = request.POST.get('security')
        if phone and security:
            if settings.SAVE_PASSWORD:
                st = FetionStatus.objects.filter(phone=phone,password=security)
            else:
                st = FetionStatus.objects.filter(phone=phone,security=security)
            if st and len(st)>0:
                request.session['phone'] = phone
                result.update({"statusCode":200,"message":u"操作成功"})
            else:
                result.update({"statusCode":300,"message":u"登录失败"})
        return HttpResponse(json.dumps(result))
    
    return render_to_response('fetion/login.html',context_instance=RequestContext(request))

def fetion_login(request):
    u'''
    引导用户完成飞信登录
    '''
    result = {"navTabId":"login","rel":"login","callbackType":"","forwardUrl":""}

    if request.method == 'POST':
        phone = request.POST.get('phone')
        password = request.POST.get('password')
        vcode = request.POST.get('vcode')
        if phone and password and vcode:
            #检查是否历史登陆用户
            status = FetionStatus.objects.filter(phone=phone)
            if status and len(status)>0 and status[0].status==FETION_STATUS_ENUM[0][0]:
                logger.info(u"已经登录,跳转查询界面:%s"%phone)
                result.update({"statusCode":300,"message":u"当前[%s]已经登录!"%phone})
                return HttpResponse(json.dumps(result))
            #登录......
            
            code = proxy.login(phone, password, vcode)
            if code == 200:
                #启动线程
                status = proxy.start_thread()
                #获取飞信用户资料
                persion = proxy.get_persion_info()
                #更新状态
                status = FetionStatus.objects.filter(phone=phone)
                if status and len(status)>0:
                    fs = status[0]
                    fs.login_ip = request.META['REMOTE_ADDR']
                    fs.status = FETION_STATUS_ENUM[0][0]
                    fs.save()
                else:
                    #第一次登陆
                    fs = FetionStatus()
                    fs.phone = phone
                    fs.uid = persion['uid']
                    fs.status = FETION_STATUS_ENUM[0][0]
                    fs.security = "".join(random.sample(['1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m'],15))
                    fs.login_ip = request.META['REMOTE_ADDR']
                    if settings.SAVE_PASSWORD:
                        fs.password = password
                    fs.save()
                request.session['phone'] = phone
                result.update({"statusCode":200,"message":u"操作成功",})
                return HttpResponse(json.dumps(result))
            elif code == 301:
                result.update({"statusCode":200,"message":u"操作成功",})
                return HttpResponse(json.dumps(result))
            elif code == 312:
                result.update({"statusCode":300,"message":u"验证码输入错误!",})
                return HttpResponse(json.dumps(result))
            elif code == 321:
                result.update({"statusCode":300,"message":u"密码输入错误!",})
                return HttpResponse(json.dumps(result))
            else:
                result.update({"statusCode":300,"message":u"未知错误!",})
                return HttpResponse(json.dumps(result))
        else:
            pass
    else:
        img_url = proxy.get_vcode_img()#读验证码
    return render_to_response('fetion/fetion_login.html',{'img_url':img_url},context_instance=RequestContext(request))
        
def fetion_query(request):
    u'''
    查询费心状态
    '''
    data = {}
    if request.method == 'POST':
        phone = request.POST.get('phone')
        security = request.POST.get('security')
        if phone and security:
            st = FetionStatus.objects.filter(phone=phone,security=security)
            if st and len(st)>0:
                data.update({'status':st[0]})
            else:
                data.update({'error':u'未找到相关记录'})
        else:
            data.update({'error':u'请填写完整的字段'})
            
    return render_to_response('fetion/fetion_query.html',data,context_instance=RequestContext(request))

@auth
def fetion_stop(request):
    u'''下线
    '''
    pass


##########队列
@auth
def list_queue(request):
    list = SMSQueue.objects.filter(phone=request.session['phone'])
    status = FetionStatus.objects.filter(phone=request.session['phone'])[0]
    
    datas = {'list':list,'status':status}
    
    if status.status == 'ONLINE':
        contact_list = proxy.get_contact_list()
        datas.update({'contact_list':contact_list['bds']})
    
    return render_to_response('fetion/queue_list.html',datas,context_instance=RequestContext(request))

@auth
def add_queue(request):
    if request.method == "POST":
        result = {"navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}
        receiver = request.POST.get('receiver',None)
        msg = request.POST.get('msg',None)
        phone = request.session.get('phone',None)
        if receiver and msg:
            queue = SMSQueue()
            queue.phone = phone
            queue.receiver = receiver
            queue.msg = msg
            queue.save()
            result.update({"statusCode":200,"message":u"操作成功"})
            return HttpResponse(json.dumps(result))
        result.update({"statusCode":300,"message":u"操作失败"})
    return HttpResponse(json.dumps(result))
    
@auth
def del_queue(request,id):
    queue = SMSQueue.objects.get(pk=id)
    if queue and queue.phone == request.session['phone']:
        queue.delete()
    result = {"statusCode":200,"message":u"操作成功","navTabId":"queue_list","rel":"queue_list","callbackType":"","forwardUrl":""}
    return HttpResponse(json.dumps(result))

@auth
def list_task(request):
    list = TaskCron.objects.filter(phone=request.session['phone'])
    status = FetionStatus.objects.filter(phone=request.session['phone'])[0]
    
    datas = {'list':list,'status':status,'tasks':TASK_ENUM}
    
    if status.status == 'ONLINE':
        contact_list = proxy.get_contact_list()
        datas.update({'contact_list':contact_list['bds']})
        
    return render_to_response('fetion/task_list.html',datas,context_instance=RequestContext(request))

@auth
def add_task(request):
    if request.method == "POST":
        result = {"navTabId":"task_list","rel":"task_list","callbackType":"","forwardUrl":""}

        phone = request.session['phone']
        cron = request.POST.get('cron',None)
        receiver = request.POST.get('receiver',None)
        task_type = request.POST.get('task_type',None)
        text = request.POST.get('text',None)
        print phone,cron,receiver,task_type
        if phone and cron and receiver and task_type:
            task = TaskCron()
            task.phone = phone
            task.cron = cron
            task.receiver = receiver
            task.task_type = task_type
            task.text = text
            task.save()
            result.update({"statusCode":200,"message":u"操作成功"})
            return HttpResponse(json.dumps(result))
        result.update({"statusCode":300,"message":u"操作失败"})
    return HttpResponse(json.dumps(result))

@auth
def del_task(request,id):
    result = {"navTabId":"task_list","rel":"task_list","callbackType":"","forwardUrl":""}
    task = TaskCron.objects.get(pk=id)
    if task and task.phone == request.session['phone']:
        task.delete()
        result.update({"statusCode":200,"message":u"操作成功"})
        return HttpResponse(json.dumps(result))
    result.update({"statusCode":300,"message":u"操作失败"})
    return HttpResponse(json.dumps(result))


